var rssreader = {};
rssreader.Application = function(){};
core.extendClass('rssreader.Application', 'core.JSApplication');

rssreader.FoldersFeeds = function(){};
core.extendClass('rssreader.FoldersFeeds', 'core.JSFrame');

rssreader.FoldersFeeds.prototype.loadContents = function(aData){
    var instance = this;
    this.showRead = aData.show_read || false;
    this.showReadMenu = {
        getText: function(){
            return instance.showRead? 'Show only unread items': 'Show all items'
        },
        handler: function(){
            instance.showRead = !instance.showRead;
            instance.send({
                method: 'changeShowRead',
                disable: instance.frame
            });
            return true;
        }
    }
    this.viewButton = new core.form.Button({
        text: 'View',
        menu: [this.showReadMenu]
    });
    this.newButton = new core.form.Button({
        text: 'New...',
        menu:[
            {
                text: 'Folder',
                handler: function(){
                    instance.send({
                        method: 'newFolder',
                        disable: instance.tree
                    });
                    return true;
                }
            },{
                text: 'Feed',
                handler: function(){
                    instance.send({
                        method: 'newFeed',
                        disable: instance.tree
                    });
                    return true;
                }
            }
        ]
    });
    this.editButton = new core.form.Button({
        disabled: true,
        text: 'Edit',
        handler: function(){
            instance.send({
                method: 'editItem',
                disable: instance.tree
            });
        }
    });
    this.removeButton = new core.form.Button({
        disabled: true,
        text: 'Remove',
        handler: function(){
            instance.send({
                method: 'removeItem',
                disable: instance.tree
            });
        }
    });
    this.frame.addToolbar(new core.Tabs({
        toolbar: true,
        elements: [this.newButton, this.editButton, this.removeButton, this.viewButton]
    }));
    this.tree = new core.tree.TreePanel({
        frame: this
    });
    this.tree.on('select', function(tree, event, item){
        instance.send({
            method: 'selectionChanged',
            message: {
                id: item?item.id: null
            }
        });
        instance.editButton.setDisabled(item?false:true);
        instance.removeButton.setDisabled(item?false:true);
        return false;
    }).on('item_click', function(tree, event, item){
        var frame = instance.application.getFrame('entries');
        instance.send({
            method: 'clickOnItem',
            message:{
                id: item.id
            },
            disable: item? (frame? frame.frame: null): null
        });
    }).on('add_item', function(tree, event, item){
        if(item.data.feed){
            item.enableDragging(tree, item, item.contentDiv);
        }
    }).on('accept_target', function(tree, e, item, target){
        if(target.data && target.data.folder)
            return true;
        return false;
    }).on('dd_end', function(tree, e, item, target){
        core.log('Moving', item.text, 'to', target.text);
        instance.send({
            method: 'moveFeed',
            message: {
                feed: item.id,
                folder: target.id
            },
            disable: instance.tree
        });
    });
    this.setContent([this.tree], '1', '1');
    this.tree.reloadTree();
};

rssreader.FolderEditor = function(){};
core.extendClass('rssreader.FolderEditor', 'core.JSDialog');

rssreader.FolderEditor.prototype.createDialog = function(aData){
    var instance = this;
    var name = new core.form.TextField({
        id: 'name'
    });
    var dlg = new core.Dialog({
        title: aData.newFolder? "New folder": "Edit folder",
        maxWidth: 400,
        data: aData,
        items: [
            core.createLabel('Name:', 'left'), name,
            core.ui.createButtons({
                buttons: ['Ok', 'Cancel'],
                align: 'right',
                handler: function(index){
                    instance.send({
                        method: index==0?'okClick':'closeDialog',
                        message: dlg.body.getValue(),
                        disable: dlg
                    });
                }
            })
        ], columns: '1', rows: '3xd',
        defaultItem: name
    });
    return dlg;
};

rssreader.FeedEditor = function(){};
core.extendClass('rssreader.FeedEditor', 'core.JSDialog');

rssreader.FeedEditor.prototype.createDialog = function(aData){
    var instance = this;
    var name = new core.form.TextField({
        id: 'name'
    });
    if(aData.newFeed){
        var url = new core.form.TextField({
            id: 'url',
            colspan: 2
        });
        var dlg = new core.Dialog({
            title: "New feed:",
            maxWidth: 450,
            data: aData,
            items: [
                core.createLabel('URL:', 'left'), core.createLabel(''),
                url,
                core.createLabel('Name:', 'left'), core.createLabel(''), name,
                new core.form.Button({
                    text: 'Fetch',
                    handler: function(){
                        instance.sendMessage('fetchFeed', dlg.body.getValue(), function(aData){
                            name.setValue(aData.name);
                        }, null, dlg);
                    }
                }),
                core.ui.createButtons({
                    colspan: 2,
                    buttons: ['Ok', 'Cancel'],
                    align: 'right',
                    handler: function(index){
                        instance.send({
                            method: index==0?'okClick':'closeDialog',
                            message: dlg.body.getValue(),
                            disable: dlg
                        });
                    }
                })
            ], columns: '1, d', rows: '5xd',
            defaultItem: url
        });
        return dlg;

    }else{
        var dlg = new core.Dialog({
            title: "Edit feed:",
            maxWidth: 400,
            data: aData,
            items: [
                core.createLabel('URL:', 'left'),
                new core.OneLineHelper({
                    text: aData.url
                }),
                core.createLabel('Name:', 'left'), name,
                core.ui.createButtons({
                    buttons: ['Ok', 'Cancel'],
                    align: 'right',
                    handler: function(index){
                        instance.send({
                            method: index==0?'okClick':'closeDialog',
                            message: dlg.body.getValue(),
                            disable: dlg
                        });
                    }
                })
            ], columns: '1', rows: '5xd',
            defaultItem: name
        });
        return dlg;
    }
};

rssreader.Entries = function(){};
core.extendClass('rssreader.Entries', 'core.JSFrame');

rssreader.Entries.prototype.loadEntryBody = function(aDiv, aContent, aComponent, aWidth){
    $(aDiv).html(aContent);
    var twidth = aWidth-25-4;
    $(aDiv).data('imgcount', $('img', aDiv).length);
    $(aDiv).data('imgload', 0);
    $('img', aDiv).addClass('rss_img').load(function(e){
        var width = 0;
        try {
            width = $(this).width();
        } catch (exception) {}

        if(width>twidth){
            var height = Math.floor(twidth/width*$(this).height());
            $(this).width(twidth).height(height);
        }
        var imgload = $(aDiv).data('imgload');
        $(aDiv).data('imgload', ++imgload);
        if(imgload==$(aDiv).data('imgcount'))
            aComponent.bodyChanged();
    });
    $('a', aDiv).attr('target', '_blank').addClass('rss_link').each(function(){
        var text = $(this).text();
        if(text && text.indexOf('http://')==0 && text.length>30){
            text = text.substr(0, 30)+'...';
            $(this).text(text);
        }
    });
    $('p', aDiv).addClass('rss_p');
//#ifdef MOBILE
    $('object', aDiv).remove();
//#endif
}

rssreader.Entries.prototype.markUnRead = function(aRowID){
    var row = this.table.getRow(aRowID);
    if(row){
        row[2] = !row[2];
        if(row[2]){
            $(row[7]).removeClass('rss_unread');
            $(row[8].chImg).addClass('checkbox_icn_off').removeClass('checkbox_icn_on');
        }else{
            $(row[7]).addClass('rss_unread');
            $(row[8].chImg).removeClass('checkbox_icn_off').addClass('checkbox_icn_on');
        }
        this.sendMessage('selectionChanged', {
            id: aRowID,
            read: row[2]
        });
    }
};

rssreader.Entries.prototype.updateForm = function(aData){
    if(!aData.header){
        this.header.setText('No feed selected');
    }else{
        this.header.setText(aData.header);
    }
    this.loadMore.setDisabled(!aData.header);
    this.markRead.setDisabled(!aData.header);
    this.frame.body.refresh(true);
};

rssreader.Entries.prototype.loadContents = function(aData){
    var instance = this;
    this.markRead = new core.form.Button({
        text: 'All read',
        tooltip: 'Mark all feeds as read',
        disabled: true,
        handler: function(){
            instance.send({
                method: 'markAsRead',
                disable: instance.frame
            });
        }
    });
    this.settingsBtn = new core.form.Button({
        text: 'Options',
        handler: function(){
            instance.send({
                method: 'showSettings',
                disable: instance.frame
            });
        }
    });
    this.loadMore = new core.form.Button({
        text: 'Load more',
        tooltip: 'Load 100 more entries',
        disabled: true,
        handler: function(){
            instance.send({
                method: 'loadMore',
                disable: instance.frame
            });
        }
    });

    this.refreshBtn = new core.form.Button({
        text: 'Refresh',
        tooltip: 'Fetch new entries',
        handler: function(){
            instance.send({
                method: 'refreshFeeds',
                disable: instance.frame
            });
        }
    });

    this.frame.addToolbar(new core.Tabs({
        toolbar: true,
        elements:[this.refreshBtn, this.markRead, this.loadMore, this.settingsBtn]
    }));

    this.pagerBox = new core.Box({
        formless: true
    });
    this.header = new core.Label({
        align: 'left',
        valign: 'middle',
        cls: 'rss_main_header',
        text: 'No feed selected'
    });
    this.table = new core.grid.GridPanel({
        allowRowSelect: true,
        pager: true,
        pagerBox: this.pagerBox,
        frame: this,
        colspan: 2,
        idIndex: 1
    });
    this.table.on('add_item', function(table, aData){
        var rootDiv = core.newDiv(null, 'rss_root');
        var titleDiv = core.newDiv(rootDiv, 'rss_title');
        var contentDiv = core.newDiv(rootDiv, 'rss_content');
        var titleText = '';
        if(aData.inFolder){
            titleText = aData.feed+' <img src="res/core/sp.png" class="icon rss_icn rss_icn_arrow"/> ';
        }
        var dateDiv = core.newDiv(titleDiv, 'rss_date');
        var titleTextSpan = core.newElement(titleDiv, 'span', 'rss_title_text');
        $(titleTextSpan).html(titleText+aData.title);
        if(!aData.read)
            $(titleTextSpan).addClass('rss_unread');
        $(dateDiv).text(aData.publishDate);
        var entryTitleDiv = core.newDiv(contentDiv, '');
        $(entryTitleDiv).html('<a href="'+aData.url+'" target="_blank" class="rss_title_link">'+aData.title+'</a>');
        var bodyDiv = core.newDiv(contentDiv, 'rss_body');
        var footerDiv = core.newDiv(contentDiv, 'rss_footer');

        var markUnread = core.newDiv(footerDiv, 'rss_checkbox');
        markUnread.chImg = core.newElement(markUnread, 'img', 'icon checkbox_icn');
        markUnread.chImg.src = 'res/core/sp.png';
        markUnread.contentSpan = core.newElement(markUnread, 'span', '');
        markUnread.rowid = aData.id;
    //    $(this.content).append(this.chImg);
        $(markUnread.contentSpan).html('&nbsp;Mark unread&nbsp;&nbsp;');
        $(markUnread).click(function(){
            instance.markUnRead(this.rowid);
        });
        var openNew = core.newDiv(footerDiv, 'rss_checkbox');
        openNew.chImg = core.newElement(openNew, 'img', 'icon rss_icn rss_icn_newwin');
        openNew.chImg.src = 'res/core/sp.png';
        openNew.rowid = aData.id;
        $(openNew).append('&nbsp;Detach topic');
        $(openNew).click(function(){
            instance.send({
                method: 'openNewWindow',
                message: {
                    id: this.rowid
                },
                disable: instance.table
            });
        });
        $(footerDiv).append('<div style="clear: both;"></div>');
        return [rootDiv, aData.id, aData.read || false, contentDiv, aData.body, false, bodyDiv, titleTextSpan, markUnread];
    }).on('select', function(table, event, id, row){
        $(row[0]).addClass('rss_selected');
        if(event.automatic)
            row[2] = !row[2];
        else
            row[2] = false;
        instance.markUnRead(id);
        if(event.automatic)
            return false;
        if(!row[5]){
            instance.loadEntryBody(row[6], row[4], table, table.width);
            row[5] = true;
        }
        $(row[3]).show();
        table.bodyChanged();
        //#ifdef MOBILE
        table.moveFrame(id);
        //#endif
        return false;
    }).on('click', function(table, event, id, row){
        if($(row[3]).css('display')=='block')
            return true;
        if(!row[5]){
            instance.loadEntryBody(row[6], row[4], table, table.width);
            row[5] = true;
        }
        $(row[3]).show();
        instance.table.bodyChanged();
        //#ifdef MOBILE
        table.moveFrame(id);
        //#endif
        return false;
    });
    this.table.on('unselect', function(el, event, id, row){
        $(row[3]).hide();
        $(row[0]).removeClass('rss_selected');
    }).on('keypress', function(table, e){
        var findUnread = function(table, aNextPage){
            for (var i = 0; i<table.getRowCount() ; i++) {
                var row = table.getRowAt(i);
                if(!row[2]){
                    table.selectRow(row[1]);
                    return false;
                }
            }
            if(table.page<table.pages && aNextPage){
                table.changePage('right', function(){
                    findUnread(table, false);
                })
            }
            return false;
        }
        
        if(e.which==32){
            var si = table.getScrollInfo(table.selected);
            if(si && si.scroll+si.frameHeight<si.rowTop+si.rowHeight){
                $(table.gridDiv).scrollTop(si.scroll+Math.floor(si.frameHeight*0.9));
                return false;
            }
            findUnread(table, true);
            return false;
        }
        return true;
    });
   this.setContent([this.header, this.pagerBox, this.table], '1, d', 'd, 1');
   this.updateForm(aData);
    this.sendMessage('loadGrid', {
        sendCounter: true
    }, function(data){
        instance.table.loadGrid(data);
    }, null, this.table);
};

rssreader.Settings = function(){};
core.extendClass('rssreader.Settings', 'core.JSDialog');

rssreader.Settings.prototype.createDialog = function(aData){
    var instance = this;
    var dlg = new core.Dialog({
        title: 'Options:',
        data: aData,
        maxWidth: 300,
        items:[
            core.createLabel('Update feeds every'),
            new core.form.TextField({
                minWidth: 130,
                id: 'update_min'
            }),
            core.createLabel('minutes', 'left'),
            core.createLabel('For each feed, keep'),
            new core.form.TextField({
                minWidth: 130,
                id: 'items_age'
            }),
            core.createLabel('items', 'left'),
            core.createLabel('Display by'),
            new core.form.TextField({
                minWidth: 130,
                id: 'show_by'
            }),
            core.createLabel('items', 'left'),
            core.createLabel('By default, load'),
            new core.form.TextField({
                minWidth: 130,
                id: 'load_total'
            }),
            core.createLabel('items', 'left'),
            new core.form.CheckBox({
                colspan: 3,
                text: 'Show notifications',
                id: 'show_notify'
            }),
            core.ui.createButtons({
                buttons: ['Save', 'Cancel'],
                colspan: 3,
                handler: function(index){
                    instance.send({
                        method: index==0?'okClick':'closeDialog',
                        message: dlg.body.getValue(),
                        disable: dlg
                    });
                }
            })
        ], rows: '6xd', columns: '1, d, d'
    });
    return dlg;
};

rssreader.OneItemViewer = function(){};
core.extendClass('rssreader.OneItemViewer', 'core.JSFrame');
rssreader.OneItemViewer.prototype.loadContents = function(aData){
    var rootDiv = core.newDiv(null, 'rss_root');
    var contentDiv = core.newDiv(rootDiv, '');
    var entryTitleDiv = core.newDiv(contentDiv, '');
    $(entryTitleDiv).html('<a href="'+aData.url+'" target="_blank" class="rss_title_link">'+aData.title+'</a>');
    this.bodyDiv = core.newDiv(contentDiv, 'rss_body');
    this.view = new core.HTMLPanel({
        html: rootDiv
    });
    this.setContent([this.view], '1', '1');
//    this.view.bodyChanged();
    var instance = this;
    this.loaded = false;
    this.frame.on('show', function(){
        if(!instance.loaded){
            rssreader.Entries.prototype.loadEntryBody(instance.bodyDiv, aData.body,
                instance.view, instance.view.width);
            instance.loaded = true;
        }
    });
//    if(this.frame.isVisible())
//        this.frame.fire('show');
};
